package com.cracker.sso.dao;

import com.alibaba.fastjson.JSONObject;
import com.cracker.sso.config.AppConfig;
import com.cracker.sso.model.TokenModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Component
public class TokenDao {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private AppConfig appConfig;

    public void save(TokenModel tokenModel) {
        redisTemplate.opsForValue().set(tokenModel.getToken(), JSONObject.toJSONString(tokenModel), appConfig.getTokenExpire(), TimeUnit.SECONDS);
    }

    public TokenModel get(String key) {
        String val = redisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(val)) {
            return null;
        }
        JSONObject jsonObject = JSONObject.parseObject(val);
        return JSONObject.toJavaObject(jsonObject, TokenModel.class);
    }

    public void delete(String key) {
        redisTemplate.delete(key);
    }

}
